﻿using Opc.Ua;
using OPCPlatformCore.Exceptions;
using OPCPlatformCore.Interfaces;
using OPCPlatformCore.Managers;
using OPCPlatformCore.Models.OPCUaModels;
using OpcUaHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OPCPlatformCore.Implementations
{
    public class OPCUaDataProvider : IOPCUaDataReader,IOPCUaDataWriter,IDisposable
    {
        OPCUaManager oPCUaManager;
        /// <summary>
        /// 特别注意,此处设计为实例化对象的时候自动连接OPCUA,因为OPCUA连接性能比较低,请仅在确实需要实例化的时候才实例化
        /// 请务必使用using语句调用此实例
        /// </summary>
        /// <param name="opcUaUrl"></param>
        public OPCUaDataProvider(string opcUaUrl)
        {
            oPCUaManager = new OPCUaManager();
            oPCUaManager.Connect(opcUaUrl);
        }

        public void Dispose()
        {
            oPCUaManager.CloseConnect();//为了避免忘记UA连接,此处将连接交给GC来实现
        }

        public OPCUaMachine GetData(OPCUaMachine oPCUaMachine)
        {
            try
            {
                OPCUaTagInfo[] readTags = oPCUaMachine.TagInfos.Where(t => t.NeedRead).ToArray();
                NodeId[] nodeIds = readTags.Select(t => new NodeId(t.Address)).ToList().ToArray();
                OpcUaClient opcUaClient = oPCUaManager.OpcUaClient;
                var temps = opcUaClient.ReadNodes(nodeIds);//同步读取数据,保证数据完整性
                for (int i = 0; i < readTags.Length; i++)
                {
                    readTags[i].SetValue(temps[i].Value.ToString());
                }
                return oPCUaMachine;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public bool WriteData(OPCUaMachine oPCUaMachine)
        {
            var writeTags = oPCUaMachine.TagInfos.Where(t => t.NeedWrite).ToList();
            var temp = writeTags.GroupBy(t => t.DataType).Select(t => t.Key);

            foreach (string key in temp)
            {
                if (!WriteData(writeTags.Where(t => t.DataType == key).ToList()))
                {
                    return false;
                }
            }
            return true;
        }

        public bool WriteData(List<OPCUaTagInfo> oPCUaTagInfos)
        {
            try
            {
                if (oPCUaTagInfos.Select(t => t.DataType).Distinct().Count() != 1)
                {
                    throw new DataTypeNotMatchException();
                }
                List<object> values = new List<object>();
                oPCUaTagInfos.ForEach(t => values.Add(oPCUaManager.ChangeObjToType(t.Value, t.DataType)));//将所有对象的值转换为对应的类型
                object[] tagValues = values.ToArray();
                string[] tagNames = oPCUaTagInfos.Select(t => t.Address).ToArray();
                OpcUaClient opcUaClient = oPCUaManager.OpcUaClient;
                return opcUaClient.WriteNodes(tagNames, tagValues);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
